<template>
  <el-card class="articles-page">
    <div class="header">
      <div class="search">
        <el-form
          :model="formInline"
          class="demo-form-inline"
          label-width="70px"
        >
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="关键字">
                <el-input v-model="formInline.articleBody"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="状态">
                <el-select v-model="formInline.status" placeholder="请选择">
                  <el-option label="启用" :value="1"> </el-option>
                  <el-option label="禁用" :value="0"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-button @click="formInline = {}">清空</el-button>
              <el-button type="primary" @click="onSubmit">搜索</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="add">

        <el-button type="success" class="el-icon-edit" @click="add"
          >新增文章</el-button
        >
      </div>
    </div>

    <el-alert
      :title="`共${counts}条记录`"
      type="info"
      show-icon
      :closable="false"
    >
    </el-alert>
    <el-table
      :header-cell-style="{ background: '#FAFAFA' }"
      :data="subjectData"
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column prop="id" label="序号" width="80"> </el-table-column>
      <el-table-column prop="title" label="文章标题"> </el-table-column>
      <el-table-column prop="visits" label="阅读数"> </el-table-column>
      <el-table-column prop="username" label="录入人"> </el-table-column>
      <el-table-column prop="addDate" label="录入时间" :formatter="dateFormat">
      </el-table-column>

      <el-table-column prop="state" label="状态" :formatter="stateFormat">
      </el-table-column>

      <el-table-column label="操作" align="center" width="220">
        <template #default="scope">
           <el-button
            type="text"
            @click="preview(scope.row.id)"
            >预览</el-button
          >
          <el-button type="text" @click="editState(scope.row)">{{
            scope.row.state === 1 ? "禁用" : "启用"
          }}</el-button>
          <el-button
            type="text"
            :disabled="scope.row.state === 1"
            @click="edit(scope.row)"
            >修改</el-button
          >
          <el-button
            type="text"
            :disabled="scope.row.state === 1"
            @click="del(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next,sizes,jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="params.page"
        :page-sizes="[10, 20, 30, 50]"
        :total="counts"
      >
      </el-pagination>
    </div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="70%"
      :close-on-click-modal="false"
    >
    <div v-if="isPreview">
      <div class="preview-box">
        <div class="preview-title">{{ articlesForm.title }}</div>
        <div class="preview-nav">
          <span>{{ articlesForm.createTime }}</span>
          <span>{{ articlesForm.username }}</span>
          <span class="el-icon-view"></span>
          <span>{{ articlesForm.visits }}</span>
        </div>
        <div class="preview-content" v-html="articlesForm.articleBody"></div>
      </div>
    </div>
     <div v-if="isAdd">
       <el-form
        ref="formRef"
        :model="articlesForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="文章标题：" prop="title" >
          <el-input v-model="articlesForm.title" placeholder="请输入文章标签">

          </el-input>
        </el-form-item>
        <el-form-item label="文章内容：" prop="articleBody">
        <quillEditor
          style="height:180px;margin-bottom: 50px;"
            v-model="articlesForm.articleBody"
             :options="editorOption"
            @blur="$refs.formRef.validateField('articleBody')"
          ></quillEditor>
        </el-form-item>
         <el-form-item label="视频地址：" prop="videoURL" >
          <el-input v-model="articlesForm.videoURL" placeholder="请输入视频地址">

          </el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
     </div>
    </el-dialog>
  </el-card>
</template>

<script>
import { list, changeState, add, detail, update, remove } from '@/api/hmmm/articles'
import { simpleSubject } from '@/api/hmmm/subjects'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

export default {
  components: {
    quillEditor
  },
  data () {
    return {
      formInline: {
        articleBody: '',
        status: null
      },
      params: {

        page: 1,
        pagesize: 10,
        articleBody: ''

      },
      title: '',
      articlesForm: {
        title: '',
        articleBody: ''
      },
      subjectData: [],
      counts: null,

      dialogVisible: false,
      isAdd: false,
      isPreview: false,

      editorOption: {
        placeholder: '请在这里输入',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['blockquote', 'code-block'], // 引用，代码块
            ['image'] // 上传图片、上传视频
          ]
        }
      },
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' }
        ],
        articleBody: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.list()
    this.simpleSubject()
  },

  methods: {
    // 切换状态
    async editState (row) {
      try {
        await changeState({
          id: row.id,
          state: row.state === 1 ? 0 : 1
        })
        this.$message.success('操作成功')
        row.state = row.state === 1 ? 0 : 1
      } catch (e) {
        this.$message.error('请求错误!')
      }
    },
    onSubmit () {
      this.params.articleBody = this.formInline.articleBody
      this.params.state = this.formInline.status

      this.list()
    },
    async list () {
      const { data } = await list(this.params)

      this.subjectData = data.items
      this.counts = data.counts
    },
    dateFormat (row) {
      return this.$dayjs(row.addDate).format('YYYY-MM-DD')
    },
    stateFormat (row) {
      if (row.state === 1) {
        return '已启用'
      } else if (row.state === 0) {
        return '已禁用'
      }
    },
    async simpleSubject () {
      const { data } = await simpleSubject()

      this.subjectOption = data
    },
    handleSizeChange (val) {
      this.params.pagesize = val
      this.list()
    },
    handleCurrentChange (current) {
      this.params.page = current
      this.list()
    },
    async add () {
      this.articlesForm = {}
      this.title = '新增文章'
      this.isAdd = true
      this.isPreview = false
      this.dialogVisible = true
      await this.$refs.formRef.resetField()
    },
    async  preview (id) {
      this.title = '预览文章'
      this.isAdd = false
      this.isPreview = true
      this.dialogVisible = true
      const { data } = await detail(id)

      this.articlesForm = data
      this.articlesForm.createTime = this.$dayjs(this.articlesForm.createTime).format('YYYY-MM-DD hh:mm:ss')
    },
    async edit (row) {
      this.title = '修改文章'
      this.isAdd = true
      this.isPreview = false
      this.dialogVisible = true

      this.articlesForm.id = row.id
      this.articlesForm.title = row.title
      this.articlesForm.articleBody = row.articleBody
    },

    async save () {
      try {
        if (this.title === '新增文章') {
          await this.$refs.formRef.validate()
          const res = await add(this.articlesForm)

          if (res.status === 200) {
            this.$message.success('添加成功')
          } else {
            this.$message.error('添加失败')
          }
        } else {
          const res = await update(this.articlesForm)
          if (res.status === 200) {
            this.$message.success('修改成功')
          } else {
            this.$message.error('修改失败')
          }
        }
        this.dialogVisible = false
        this.list()
      } catch (err) {
        this.$message.error(err.response.data)
      }
    },
    async del (row) {
      await this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await remove(row)

      this.$message({
        type: 'success',
        message: '删除成功!'
      })
      this.list()
    }
  }
}
</script>

<style scoped lang="scss">
.articles-page {
  margin: 20px 20px;
  .header {
    display: flex;
    justify-content: space-between;
  }
  .pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
  .el-dialog {
    .preview-box {
  .preview-title {
    font-size: 25px;
    font-weight: 700;
    margin-bottom: 10px;
  }
  .preview-nav {
    span {
      margin-right: 10px;
    }
  }
  .preview-content {
    margin-top: 10px;
    padding: 10px;
    background-color: #f5f5f5;
    border-top: 1px dashed #ccc;
  }
}
    .dialog-footer {
      display: block;
      text-align: center;
    }
  }
}
</style>
